﻿
using LDM.Framework.Caches;
using LDM.Sys.ServiceAPI.Enum;
using LDM.Sys.ServiceAPI.Model.DBModel;
using LDM.Sys.ServiceAPI.Model.ViewModel.Request.AuthorityReq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model.Enum.ConfigModel;
using Model.Models;
using User.Repositories.Repository.Interfaces;
using Utility.DB.SqlSugar;
using Utility.Extensions;

namespace User.Repositories.Repository
{
    /// <summary>
    /// 微信用户实现
    /// </summary>
    public class WxAccountRepository : DbContextBase<WxAccount>, IWxAccountRepository, ITransient
    {
        private readonly IMemoryCache _memoryCache;
        private readonly string key = "UserInfo";
        public WxAccountRepository(IConfiguration configuration, IMemoryCache memoryCache) :
            base(configuration.GetConnectionString(ConnectionStringType.UserMysql.GetDescription()))
        {
            _memoryCache = memoryCache;
        }


        /// <summary>
        /// 根据opendid获取用户信息
        /// </summary>
        public WxAccount GetUserByOpenId(string openid)
        {
            if (string.IsNullOrWhiteSpace(openid))
                return null;
            return Db.Queryable<WxAccount>()
                .WhereIF(!string.IsNullOrWhiteSpace(openid), x => x.OpenId.Equals(openid))
                .Single();
        }



        /// <summary>
        /// 获取邮件或者email是否被注册
        /// </summary>
        public WxAccount GetSendEmailByEmailName(string phone, string email)
        {
            if (string.IsNullOrWhiteSpace(phone) && string.IsNullOrWhiteSpace(email))
                return null;
            return Db.Queryable<WxAccount>()
                .WhereIF(!string.IsNullOrWhiteSpace(phone), x => x.Phone.Equals(phone))
                .WhereIF(!string.IsNullOrWhiteSpace(email), x => x.Email.Equals(email))
                .Single();
        }


        /// <summary>
        /// 获取邮件或者email是否被注册
        /// </summary>
        public WxAccount GetUserLogin(string phone, string email, string password)
        {
            if (string.IsNullOrWhiteSpace(phone) && string.IsNullOrWhiteSpace(email))
                return null;
            return Db.Queryable<WxAccount>()
                .Where(x => x.Password.Equals(password) && x.StatusFlag)
                .WhereIF(!string.IsNullOrWhiteSpace(phone), x => x.Phone.Equals(phone))
                .WhereIF(!string.IsNullOrWhiteSpace(email), x => x.Email.Equals(email))
                .Single();
        }

        /// <summary>
        /// 根据userid获取用户信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public WxAccount GetUserInfo(string userid)
        {
            return _memoryCache.GetFromCacheFirst(key, () => Db.Queryable<WxAccount>().InSingle(userid), 60);
        }
    }
}
